package com.dylan.历史.java8.StreamAPI;

import java.util.Comparator;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/23.
 */
public class Stream处理2 {

    public static void main(String[] args) {
//        Stream<String> words = getWords();

        // 去重
        Stream<String> uniqueWords = getWords().distinct();
//        uniqueWords.forEach(System.out::println);

        // 排序.其中 Comparator.comparing() 里必须写String::length ,因为写 s -> s.length() 无法判断类型.除非lambda表达式作为参数传入
        Stream<String> sortedWords = getWords().sorted(Comparator.comparing(String::length).reversed());
//        Function<String, Integer> keyExtractor = s -> s.length();
//        Stream<String> sortedWords = getWords().sorted(Comparator.comparing(keyExtractor).reversed());
//        sortedWords.forEach(System.out::println);

        // 数量
        long count = getWords().count();
//        System.out.println("count: " + count);

        // 最大值
        Optional<String> large = getWords().max(String::compareToIgnoreCase);
        large.ifPresent(System.out::println);

        // 返回第一个
        Optional<String> startWithT1 = getWords().filter(s -> s.startsWith("T")).findFirst();
        startWithT1.ifPresent(System.out::println);

        // 返回任意一个,可以并行计算
        Optional<String> startWithT2 = getWords().parallel().filter(s -> s.startsWith("T")).findAny();
        startWithT2.ifPresent(System.out::println);

        // 判断是否存在匹配
        boolean aWordStartsWithT = getWords().parallel().anyMatch(s -> s.startsWith("T"));
        System.out.println("aWordStartsWithT: " + aWordStartsWithT);

        // 判断是否全部匹配
        boolean allMatch = getWords().parallel().allMatch(s -> s.length() >= 1);

        // 判断是否全不匹配
        boolean noneMatch = getWords().parallel().allMatch(s -> s.length() == 0);
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
